import React, { useState, useEffect } from 'react';
import { Input, Upload, Button, message } from 'antd';
import { SendOutlined, PictureOutlined } from '@ant-design/icons';
import ChatMessage from '@/components/ChatMessage/ChatMessage';
import { io } from 'socket.io-client';
import './Chat.page.css';

interface Message {
    content: string;
    type: 'text' | 'image';
    sender: 'user' | 'expert';
    timestamp?: string;
    user_id?: string;
}

const ChatPage: React.FC = () => {
    const [messages, setMessages] = useState<Message[]>([]);
    const [inputText, setInputText] = useState('');
    const [socket, setSocket] = useState<any>(null);
    const [userId, setUserId] = useState<string>('');
    const [room] = useState('default_room'); // 可以根据需要动态设置房间

    useEffect(() => {
        const newSocket = io('http://localhost:8980');
        setSocket(newSocket);

        newSocket.on('connect_response', (data) => {
            if (data.status === 'success') {
                setUserId(data.user_id);
                newSocket.emit('join', { room, user_id: data.user_id });
            } else {
                message.error('连接失败：' + data.message);
            }
        });

        return () => {
            if (newSocket) {
                newSocket.emit('leave', { room, user_id: userId });
                newSocket.disconnect();
            }
        };
    }, []);

    useEffect(() => {
        if (!socket) return;

        const messageHandler = (data: any) => {
            const newMessage: Message = {
                content: data.message,
                type: data.type || 'text',
                sender: data.user_id === userId ? 'user' : 'expert',
                timestamp: data.timestamp,
                user_id: data.user_id
            };
            setMessages(prev => [...prev, newMessage]);
        };

        socket.on('new_message', messageHandler);

        return () => {
            socket.off('new_message', messageHandler);
        };
    }, [socket, userId]);

    const handleSendMessage = () => {
        if (!inputText.trim() || !socket) return;

        socket.emit('message', {
            room,
            message: inputText,
            user_id: userId
        });

        setInputText('');
    };

    const handleImageUpload = (info: any) => {
        const { status, response } = info.file;

        if (status === 'uploading') {
            const tempMessage: Message = {
                content: '图片上传中...',
                type: 'text',
                sender: 'user',
                user_id: userId
            };
            setMessages(prev => [...prev, tempMessage]);
        } else if (status === 'done' && socket && response?.url) {
            setMessages(prev => prev.filter(msg =>
                !(msg.content === '图片上传中...' && msg.sender === 'user' && msg.user_id === userId)
            ));

            socket.emit('message', {
                room,
                message: response.url,
                type: 'image',
                user_id: userId
            });
        } else if (status === 'error') {
            setMessages(prev => prev.filter(msg =>
                !(msg.content === '图片上传中...' && msg.sender === 'user' && msg.user_id === userId)
            ));

            const errorMessage: Message = {
                content: '图片上传失败，请重试',
                type: 'text',
                sender: 'user',
                user_id: userId
            };
            setMessages(prev => [...prev, errorMessage]);
        }
    };

    return (
        <div className="chat-container">
            <div className="messages-container">
                {messages.map((msg, index) => (
                    <ChatMessage
                        key={index}
                        content={msg.content}
                        type={msg.type}
                        sender={msg.sender}
                    />
                ))}
            </div>
            <div className="input-container">
                <Upload
                    name="image"
                    showUploadList={false}
                    action="/app-api/upload"
                    onChange={handleImageUpload}
                >
                    <Button
                        icon={<PictureOutlined />}
                        className="upload-button"
                        type="text"
                    />
                </Upload>
                <Input
                    value={inputText}
                    onChange={(e) => setInputText(e.target.value)}
                    onPressEnter={handleSendMessage}
                    placeholder="输入消息..."
                />
                <Button
                    type="primary"
                    icon={<SendOutlined />}
                    onClick={handleSendMessage}
                >
                    发送
                </Button>
            </div>
        </div>
    );
};

export default ChatPage;